<template>
    <div>
        <!-- 顶部标签切换 -->
        <div style="padding: 20px 20px 0 20px;">
            <el-tabs v-model="activeMenu" @tab-click="handleTabClick">
                <el-tab-pane label="分类管理" name="collections">
                    <span slot="label">
                        <i class="el-icon-folder"></i>
                        分类管理
                    </span>
                </el-tab-pane>
                <el-tab-pane label="素材管理" name="materials">
                    <span slot="label">
                        <i class="el-icon-picture"></i>
                        素材管理
                    </span>
                </el-tab-pane>
            </el-tabs>
        </div>

        <!-- 内容区 -->
        <div style="padding: 0 20px 20px 20px;">
            <!-- 分类管理页面 -->
            <div v-show="activeMenu === 'collections'">
                <el-card>
                    <div slot="header" class="clearfix">
                        <span style="font-size: 18px; font-weight: bold;">分类管理</span>
                        <el-button type="primary" style="float: right;" @click="openCollectionDialog()">
                            新增分类
                        </el-button>
                    </div>

                    <el-table :data="collectionList" :loading="collectionLoading" border>
                        <el-table-column prop="min_version" label="最低版本" width="120" align="center" />
                        <el-table-column prop="max_version" label="最高版本" width="120" align="center" />
                        <el-table-column prop="name" label="分类名称" align="center" />
                        <el-table-column prop="color" label="色值" align="center" />
                        <el-table-column prop="opacity" label="透明度" align="center" />
                        <el-table-column prop="blur" label="模糊" align="center" />
                        <el-table-column prop="sort_order" label="排序值" width="100" align="center" />
                        <el-table-column prop="updated_at" label="修改时间" width="160" align="center" />

                        <!-- <el-table-column prop="created_at" label="创建时间" width="180" align="center" /> -->
                        <el-table-column label="操作" width="200" align="center">
                            <template slot-scope="scope">
                                <el-button type="primary" size="mini" @click="openCollectionDialog(scope.row)">
                                    编辑
                                </el-button>
                                <el-button type="danger" size="mini" @click="deleteCollection(scope.row)">
                                    删除
                                </el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-card>
            </div>

            <!-- 素材管理页面 -->
            <div v-show="activeMenu === 'materials'">
                <el-card>
                    <!-- 查询表单 -->
                    <el-form :inline="true" style="margin-bottom: 20px;">
                        <el-form-item label="版本号">
                            <el-input v-model="materialQuery.version" @keyup.enter.native="fetchMaterialList" clearable
                                placeholder="支持1.2.3格式" />
                        </el-form-item>
                        <el-form-item label="视觉集合">
                            <el-select v-model="materialQuery.visual_collection_id" clearable placeholder="请选择分类">
                                <el-option v-for="item in enabledCollections" :key="item.id" :label="item.name"
                                    :value="item.id" />
                            </el-select>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" @click="fetchMaterialList">查询</el-button>
                            <el-button @click="resetMaterialQuery">重置</el-button>
                        </el-form-item>
                    </el-form>

                    <div style="margin-bottom:15px;text-align:right">
                        <el-button type="primary" @click="openMaterialDialog()">新增素材</el-button>
                    </div>

                    <el-table :data="materialList" :loading="materialLoading" border>
                        <el-table-column prop="min_version" label="最低版本" width="120" align="center" />
                        <el-table-column prop="max_version" label="最高版本" width="120" align="center" />
                        <el-table-column prop="visual_collection_name" label="视觉集合" width="120" align="center" />
                        <el-table-column prop="theme_tags" label="主题标签" align="center">
                            <template slot-scope="scope">
                                <el-tag v-for="tag in parseCommaSeparated(scope.row.theme_tags)" :key="tag" size="mini"
                                    style="margin: 2px;">
                                    {{ tag }}
                                </el-tag>
                            </template>
                        </el-table-column>
                        <el-table-column prop="main_text_material" label="主文字素材" width="120" align="center" />
                        <el-table-column prop="extra_text_materials" label="副文字素材" width="120" align="center" />
                        <el-table-column label="订阅要求" width="100" align="center">
                            <template slot-scope="scope">
                                <el-tag :type="scope.row.is_subscription_required === 1 ? 'warning' : 'success'">
                                    {{ scope.row.is_subscription_required === 1 ? '需订阅' : '免费' }}
                                </el-tag>
                            </template>
                        </el-table-column>
                        <el-table-column label="缩略图" width="100" align="center">
                            <template slot-scope="scope">
                                <el-image v-if="scope.row.thumbnail_url" :src="scope.row.thumbnail_url"
                                    style="width: 50px; height: 50px; border-radius: 4px;"
                                    :preview-src-list="[scope.row.thumbnail_url]" fit="cover" />
                                <span v-else style="color: #999;">无图片</span>
                            </template>
                        </el-table-column>
                        <el-table-column prop="updated_at" label="修改时间" width="160" align="center" />
                        <el-table-column label="操作" width="200" align="center">
                            <template slot-scope="scope">
                                <el-button type="primary" size="mini" @click="openMaterialDialog(scope.row)">
                                    编辑
                                </el-button>
                                <el-button type="danger" size="mini" @click="deleteMaterial(scope.row)">
                                    删除
                                </el-button>
                            </template>
                        </el-table-column>
                    </el-table>

                    <el-pagination v-if="materialTotal > 0" :current-page.sync="materialQuery.page"
                        :page-size.sync="materialQuery.pageSize" :total="materialTotal"
                        @current-change="fetchMaterialList" @size-change="fetchMaterialList"
                        style="margin:20px 0; text-align:center" />
                </el-card>
            </div>
        </div>

        <!-- 分类弹窗 -->
        <el-dialog :visible.sync="collectionDialogVisible" :title="collectionForm.id ? '编辑分类' : '新增分类'" width="500px"
            :before-close="handleCollectionClose">
            <el-form :model="collectionForm" ref="collectionForm" :rules="collectionRules" label-width="100px">
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="最低版本" prop="min_version">
                            <el-input v-model="collectionForm.min_version" placeholder="如：1.0.0" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="最高版本" prop="max_version">
                            <el-input v-model="collectionForm.max_version" placeholder="如：2.5.3" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-form-item label="key" prop="name">
                    <el-input v-model="collectionForm.name" placeholder="请输入key" />
                </el-form-item>
                <!-- 多语言选择 -->
                <el-form-item label="多语言" prop="langs">
                    <el-select v-model="selectedLangs" multiple filterable placeholder="请选择语言" style="width: 100%"
                        @change="onLangChange">
                        <el-option v-for="opt in allLangOptions" :key="opt.value" :label="opt.label"
                            :value="opt.value" />
                    </el-select>
                </el-form-item>
                <!-- 动态各语言对应名称输入框 -->
                <template v-for="lang in selectedLangs">
                    <el-form-item :key="lang" :label="getLangLabel(lang)">
                        <el-input v-model="langNameMap[lang]" :placeholder="`请输入${getLangLabel(lang)}名称`" />
                    </el-form-item>
                </template>

                <el-form-item label="色值" prop="color">
                    <el-input v-model="collectionForm.color" placeholder="请输入色值" />
                </el-form-item>
                <el-form-item label="透明度" prop="opacity">
                    <el-input v-model="collectionForm.opacity" placeholder="请输入透明度" />
                </el-form-item>
                <el-form-item label="模糊" prop="blur">
                    <el-input v-model="collectionForm.blur" placeholder="请输入模糊" />
                </el-form-item>
                <el-form-item label="排序值" prop="sort_order">
                    <el-input-number v-model="collectionForm.sort_order" :min="0" :max="9999" controls-position="right"
                        style="width: 100%;" />
                </el-form-item>
                <!-- <el-form-item label="状态" prop="status">
                    <el-radio-group v-model="collectionForm.status">
                        <el-radio :label="1">启用</el-radio>
                        <el-radio :label="0">禁用</el-radio>
                    </el-radio-group>
                </el-form-item> -->
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="collectionDialogVisible = false">取 消</el-button>
                <el-button type="primary" :loading="collectionSaveLoading" @click="handleCollectionSave">
                    确 定
                </el-button>
            </div>
        </el-dialog>

        <!-- 素材弹窗 -->
        <el-dialog :visible.sync="materialDialogVisible" :title="materialForm.id ? '编辑素材' : '新增素材'" width="800px"
            :before-close="handleMaterialClose">
            <el-form :model="materialForm" ref="materialForm" :rules="materialRules" label-width="120px">
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="最低版本" prop="min_version">
                            <el-input v-model="materialForm.min_version" placeholder="如：1.0.0" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="最高版本" prop="max_version">
                            <el-input v-model="materialForm.max_version" placeholder="如：2.5.3" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-form-item label="视觉集合" prop="visual_collection_id">
                    <el-select v-model="materialForm.visual_collection_id" placeholder="请选择分类" style="width: 100%;"
                        @change="updateVisualCollectionName">
                        <el-option v-for="item in enabledCollections" :key="item.id" :label="item.name"
                            :value="item.id" />
                    </el-select>
                </el-form-item>
                <el-form-item label="排序" prop="sort_order">
                    <el-input-number v-model="materialForm.sort_order" :min="0" :max="9999" />
                </el-form-item>
                <el-form-item label="主题标签" prop="theme_tags">
                    <el-select v-model="materialForm.theme_tags" multiple placeholder="请选择" style="width:100%;">
                        <el-option v-for="item in themeTagOptions" :key="item.value" :label="item.label"
                            :value="item.value" />
                    </el-select>
                </el-form-item>
                <el-form-item label="主文字素材" prop="main_text_material">
                    <el-select v-model="materialForm.main_text_material" placeholder="请选择" style="width:100%;">
                        <el-option v-for="item in extraTextOptions" :key="item.value" :label="item.label"
                            :value="item.value" :disabled="materialForm.extra_text_materials.includes(item.value)" />
                    </el-select>
                </el-form-item>

                <el-form-item label="副文字素材" prop="extra_text_materials">
                    <el-select v-model="materialForm.extra_text_materials" multiple placeholder="请选择"
                        style="width:100%;">
                        <el-option v-for="item in extraTextOptions" :key="item.value" :label="item.label"
                            :value="item.value" :disabled="materialForm.main_text_material === item.value" />
                    </el-select>
                </el-form-item>

                <el-form-item label="订阅要求" prop="is_subscription_required">
                    <el-radio-group v-model="materialForm.is_subscription_required">
                        <el-radio :label="0">免费</el-radio>
                        <el-radio :label="1">需订阅</el-radio>
                    </el-radio-group>
                </el-form-item>

                <!-- 封面图上传 -->
                <el-form-item label="封面图" prop="thumbnail_url">
                    <el-upload class="img-uploader" action="https://xiaoshuchengzhang.com/node/Tarot/upload"
                        :show-file-list="false" :on-success="(res) => handleUploadedFile(res, 'thumbnail_url')"
                        :before-upload="() => beforeUploadImg('thumbnail')" :accept="'image/*'">
                        <template v-if="!materialForm.thumbnail_url">
                            <div style="position:relative;width:88px;height:88px;">
                                <i class="el-icon-plus img-uploader-icon"></i>
                                <i v-if="uploadLoading.thumbnail" class="el-icon-loading"
                                    style="position:absolute;top:44px;left:24px;font-size:40px;color:#409EFF"></i>
                            </div>
                        </template>
                        <template v-else>
                            <img :src="materialForm.thumbnail_url" class="img-preview" />
                            <el-button class="img-delete" icon="el-icon-delete" size="mini"
                                @click="handleDeleteFile('thumbnail_url', $event)" circle plain type="danger" />
                        </template>
                    </el-upload>
                </el-form-item>
                <el-form-item label="上传类型" prop="upload_type">
                    <el-radio-group v-model="materialForm.upload_type">
                        <el-radio :label="1">图片</el-radio>
                        <el-radio :label="2">视频</el-radio>
                    </el-radio-group>
                </el-form-item>
                <!-- 原图上传 -->
                <el-form-item label="原图" prop="original_image_url" v-if="materialForm.upload_type === 1">
                    <el-upload class="img-uploader" action="https://xiaoshuchengzhang.com/node/Tarot/upload"
                        :show-file-list="false" :on-success="(res) => handleUploadedFile(res, 'original_image_url')"
                        :before-upload="() => beforeUploadImg('original')" :accept="'image/*'">
                        <template v-if="!materialForm.original_image_url">
                            <div style="position:relative;width:88px;height:88px;">
                                <i class="el-icon-plus img-uploader-icon"></i>
                                <i v-if="uploadLoading.original" class="el-icon-loading"
                                    style="position:absolute;top:44px;left:24px;font-size:40px;color:#409EFF"></i>
                            </div>
                        </template>
                        <template v-else>
                            <img :src="materialForm.original_image_url" class="img-preview" />
                            <el-button class="img-delete" icon="el-icon-delete" size="mini"
                                @click="handleDeleteFile('original_image_url', $event)" circle plain type="danger" />
                        </template>
                    </el-upload>
                </el-form-item>

                <!-- 视频上传 -->
                <el-form-item label="视频" prop="video_url" v-if="materialForm.upload_type === 2">
                    <el-upload class="img-uploader" action="https://xiaoshuchengzhang.com/node/Tarot/upload"
                        :show-file-list="false" :on-success="(res) => handleUploadedFile(res, 'video_url')"
                        :before-upload="beforeUploadVideo" :accept="'video/*'">
                        <template v-if="!materialForm.video_url">
                            <div style="position:relative;width:88px;height:88px;">
                                <i class="el-icon-plus img-uploader-icon"></i>
                                <i v-if="uploadLoading.video" class="el-icon-loading"
                                    style="position:absolute;top:44px;left:24px;font-size:40px;color:#409EFF"></i>
                            </div>
                        </template>
                        <template v-else>
                            <video controls :src="materialForm.video_url" class="video-preview"></video>
                            <el-button class="img-delete" icon="el-icon-delete" size="mini"
                                @click="handleDeleteFile('video_url', $event)" circle plain type="danger" />
                        </template>
                    </el-upload>
                </el-form-item>

            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="materialDialogVisible = false">取 消</el-button>
                <el-button type="primary" :loading="materialSaveLoading" @click="handleMaterialSave">
                    确 定
                </el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import axios from 'axios'

export default {
    data() {
        return {
            activeMenu: 'collections',

            // 分类相关
            collectionList: [],
            collectionLoading: false,
            collectionDialogVisible: false,
            collectionSaveLoading: false,
            collectionForm: {
                langs: []
            },
            allLangOptions: [
                { label: '简中', value: 'zh-Hans' },
                { label: '繁中', value: 'zh-Hant' },
                { label: '英文', value: 'en-US' },
                { label: '俄语', value: 'ru' },
                { label: '法语', value: 'fr' },
                { label: '西班牙语', value: 'es' },
                { label: '葡萄牙语(巴西)', value: 'pt-BR' },
                { label: '德语', value: 'de' },
                { label: '阿拉伯语', value: 'ar' },
                { label: '印地语', value: 'hi' }
            ],
            selectedLangs: [], // 已选语言
            langNameMap: {},   // { 语言: 名称 } 用于动态输入
            collectionRules: {
                min_version: [
                    { required: true, message: '必填', trigger: 'blur' },
                    { pattern: /^\d+\.\d+\.\d+$/, message: '格式为1.0.0', trigger: 'blur' }
                ],
                max_version: [
                    { required: true, message: '必填', trigger: 'blur' },
                    { pattern: /^\d+\.\d+\.\d+$/, message: '格式为1.0.0', trigger: 'blur' }
                ],
                name: [
                    { required: true, message: '请输入分类名称', trigger: 'blur' }
                ],
                sort_order: [
                    { required: true, message: '请输入排序值', trigger: 'blur' }
                ],
                status: [
                    { required: true, message: '请选择状态', trigger: 'change' }
                ]
            },

            // 素材相关
            materialList: [],
            materialTotal: 0,
            materialLoading: false,
            materialDialogVisible: false,
            materialSaveLoading: false,
            materialQuery: {
                version: '',
                visual_collection_id: '',
                page: 1,
                pageSize: 10
            },
            materialForm: {
                main_text_material: '',
                extra_text_materials: [], // 必须是数组，且不设为null！
                is_subscription_required: 0,
                upload_type: 1,
                original_image_url: '',
                video_url: '',
            },
            materialRules: {
                min_version: [
                    { required: true, message: '必填', trigger: 'blur' },
                    { pattern: /^\d+\.\d+\.\d+$/, message: '格式为1.0.0', trigger: 'blur' }
                ],
                max_version: [
                    { required: true, message: '必填', trigger: 'blur' },
                    { pattern: /^\d+\.\d+\.\d+$/, message: '格式为1.0.0', trigger: 'blur' }
                ],
                visual_collection_id: [
                    { required: true, message: '请选择视觉集合', trigger: 'change' }
                ],
                sort_order: [
                    { type: 'number', required: true, message: '请输入排序值', trigger: 'blur' }
                ],
                theme_tags: [
                    { type: 'array', required: true, min: 1, message: '请至少选择一个主题标签', trigger: 'change' }
                ],
                main_text_material: [
                    { required: true, message: '请选择主文字素材', trigger: 'change' }
                ],
                extra_text_materials: [
                    { type: 'array', required: true, min: 1, message: '请至少选择一个副文字素材', trigger: 'change' }
                ],
                is_subscription_required: [
                    { required: true, message: '请选择是否订阅', trigger: 'change' }
                ],
                thumbnail_url: [
                    { required: true, message: '请上传缩略图', trigger: 'change' }
                ],
                original_image_url: [
                    { validator: this.validateImageOrVideo, trigger: 'change' }
                ],
                video_url: [
                    { validator: this.validateImageOrVideo, trigger: 'change' }
                ],
            },
            uploadLoading: {
                thumbnail: false,
                original: false,
                video: false
            },
            themeTagOptions: [
                { label: "财富", value: "wealth" },
                { label: "艰难时刻", value: "tough_times" },
                { label: "人际交往", value: "social_interaction" },
                { label: "美丽与形象", value: "beauty_and_image" },
                { label: "自我关怀", value: "self_care" },
                { label: "关注健康", value: "health_focus" },
                { label: "浪漫关系", value: "romance" },
                { label: "自我成长", value: "self_growth" },
                { label: "事业与发展", value: "career_and_growth" },
                { label: "治愈之旅", value: "healing_journey" },
                { label: "感恩与欣赏", value: "gratitude" },
                { label: "放松与解压", value: "relaxation" },
                { label: "综合", value: "comprehensive" }
            ],
            extraTextOptions: [
                { label: "A", value: "A" },
                { label: "B", value: "B" },
                { label: "C", value: "C" },
                { label: "D", value: "D" },
                { label: "E", value: "E" },
                { label: "F", value: "F" },
                { label: "G", value: "G" }
            ],
            theme_tags: [],
            extra_text_materials: [],
            main_text_material: '',  // 单值
        }
    },
    watch: {
        'materialForm.main_text_material'(val) {
            if (val && this.materialForm.extra_text_materials.includes(val)) {
                this.materialForm.extra_text_materials =
                    this.materialForm.extra_text_materials.filter(v => v !== val);
            }
        },
        'materialForm.extra_text_materials'(arr) {
            if (this.materialForm.main_text_material
                && arr.includes(this.materialForm.main_text_material)) {
                this.materialForm.main_text_material = '';
            }
        }
    },
    computed: {
        enabledCollections() {
            return this.collectionList.filter(item => item.status === 1);
        }
    },
    methods: {
        handleUploadTypeChange(val) {
            if (val === 1) {
                // 选择图片时，清空视频相关字段
                this.materialForm.video_url = '';
            } else if (val === 2) {
                // 选择视频时，清空图片相关字段
                this.materialForm.original_image_url = '';
            }

            // 触发表单验证更新
            this.$nextTick(() => {
                if (this.$refs.materialForm) {
                    this.$refs.materialForm.validateField(['original_image_url', 'video_url']);
                }
            });
        },
        validateImageOrVideo(rule, value, callback) {
            const type = this.materialForm.upload_type;
            if (type === 1) {
                if (!this.materialForm.original_image_url) {
                    callback(new Error("请上传原图"));
                } else {
                    callback();
                }
            } else if (type === 2) {
                if (!this.materialForm.video_url) {
                    callback(new Error("请上传视频"));
                } else {
                    callback();
                }
            } else {
                callback(new Error("请选择上传类型"));
            }
        },
        beforeUploadImg(type) {
            // type = 'thumbnail' | 'original'
            this.uploadLoading[type] = true;
            return true;
        },
        // 上传前检查（为视频上传添加专门的检查）
        beforeUploadVideo(file) {
            this.uploadLoading.video = true;

            // 检查文件类型
            const isVideo = file.type.startsWith('video/');
            if (!isVideo) {
                this.$message.error('只能上传视频文件！');
                this.uploadLoading.video = false;
                return false;
            }

            // 检查文件大小（可选，比如限制100MB）
            const isLt100M = file.size / 1024 / 1024 < 100;
            if (!isLt100M) {
                this.$message.error('视频文件大小不能超过 100MB!');
                this.uploadLoading.video = false;
                return false;
            }

            return true;
        },
        // 删除文件处理
        handleDeleteFile(field, event) {
            // 阻止事件冒泡，防止触发上传
            if (event) {
                event.stopPropagation();
                event.preventDefault();
            }

            this.materialForm[field] = '';

            // 删除后触发验证
            this.$nextTick(() => {
                if (this.$refs.materialForm) {
                    this.$refs.materialForm.validateField([field]);
                }
            });
        },
        handleUploadedFile(res, field) {
            // field: 'thumbnail_url' | 'original_image_url' | 'video_url'
            // 先还原loading
            if (field === 'thumbnail_url') this.uploadLoading.thumbnail = false;
            if (field === 'original_image_url') this.uploadLoading.original = false;
            if (field === 'video_url') this.uploadLoading.video = false;

            if (res && res.code === 0 && res.fileUrl) {
                this.materialForm[field] = res.fileUrl;
                this.$message.success('上传成功');

                // 上传成功后触发验证更新
                this.$nextTick(() => {
                    if (this.$refs.materialForm) {
                        this.$refs.materialForm.validateField([field]);
                    }
                });
            } else {
                this.$message.error('上传失败');
            }
        },
        handleTabClick(tab) {
            this.activeMenu = tab.name;
            if (tab.name === 'collections') {
                this.fetchCollectionList();
            } else if (tab.name === 'materials') {
                this.fetchMaterialList();
            }
        },

        // 分类相关方法
        async fetchCollectionList() {
            this.collectionLoading = true;
            try {
                const { data } = await axios.post('https://xiaoshuchengzhang.com/node/Tarot/visualCollection/list', {
                    page: 1,
                    pageSize: 100
                });

                if (data.code === 0) {
                    this.collectionList = data.data.list || data.data;
                } else {
                    this.$message.error(data.msg || '获取分类列表失败');
                }
            } catch (error) {
                console.error('获取分类列表失败:', error);
                this.$message.error('获取分类列表失败');
            } finally {
                this.collectionLoading = false;
            }
        },
        // 选项change时，重置或同步 langNameMap
        onLangChange(val) {
            // 移除未选中语言的 name
            Object.keys(this.langNameMap).forEach(lang => {
                if (!val.includes(lang)) {
                    this.$delete(this.langNameMap, lang);
                }
            });
            // 初始化新加的选项项
            val.forEach(lang => {
                if (!(lang in this.langNameMap)) {
                    this.$set(this.langNameMap, lang, '');
                }
            });
        },
        // 获取多语言选项中文名
        getLangLabel(lang) {
            const found = this.allLangOptions.find(o => o.value === lang);
            return found ? found.label : lang;
        },
        // 打开弹窗时（含回显处理）
        openCollectionDialog(row) {
            if (row) {
                this.collectionForm = { ...row };
                // 兼容已有数据
                const langsList = Array.isArray(row.langs)
                    ? row.langs
                    : (row.langs ? JSON.parse(row.langs) : []);
                // 回显选中的语言
                this.selectedLangs = langsList.map(i => i.lang);
                // 回显已填内容
                this.langNameMap = {};
                langsList.forEach(i => {
                    this.$set(this.langNameMap, i.lang, i.name);
                });
            } else {
                // 新增清理
                this.collectionForm = { name: '', sort_order: 0, status: 1, langs: [] };
                this.selectedLangs = [];
                this.langNameMap = {};
            }
            this.collectionDialogVisible = true;
            this.$nextTick(() => {
                this.$refs.collectionForm && this.$refs.collectionForm.clearValidate();
            });
        },

        async handleCollectionSave() {
            this.collectionForm.langs = this.selectedLangs.map(lang => ({
                lang,
                name: this.langNameMap[lang] || ''
            }));
            await this.$refs.collectionForm.validate();
            
            this.collectionSaveLoading = true;
            
            try {
                const { data } = await axios.post('https://xiaoshuchengzhang.com/node/Tarot/visualCollection/save', this.collectionForm);

                if (data.code === 0) {
                    this.$message.success('保存成功');
                    this.collectionDialogVisible = false;
                    this.fetchCollectionList();
                } else {
                    this.$message.error(data.msg || '保存失败');
                }
            } catch (error) {
                console.error('保存失败:', error);
                this.$message.error('保存失败');
            } finally {
                this.collectionSaveLoading = false;
            }
        },

        deleteCollection(row) {
            this.$confirm('确定要删除此分类吗？', '提示', { type: 'warning' }).then(async () => {
                try {
                    const { data } = await axios.post('https://xiaoshuchengzhang.com/node/Tarot/visualCollection/delete', { id: row.id });

                    if (data.code === 0) {
                        this.$message.success('删除成功');
                        this.fetchCollectionList();
                    } else {
                        this.$message.error(data.msg || '删除失败');
                    }
                } catch (error) {
                    console.error('删除失败:', error);
                    this.$message.error('删除失败');
                }
            });
        },

        handleCollectionClose() {
            this.collectionDialogVisible = false;
            this.$nextTick(() => {
                if (this.$refs.collectionForm) {
                    this.$refs.collectionForm.clearValidate();
                }
            });
        },

        // 素材相关方法
        async fetchMaterialList() {
            this.materialLoading = true;
            try {
                const { data } = await axios.post('https://xiaoshuchengzhang.com/node/Tarot/visualMaterial/list', {
                    page: this.materialQuery.page,
                    pageSize: this.materialQuery.pageSize,
                    version: this.materialQuery.version,
                    visual_collection_id: this.materialQuery.visual_collection_id
                });

                if (data.code === 0) {
                    this.materialList = data.data.list || [];
                    this.materialTotal = data.data.total || 0;
                } else {
                    this.$message.error(data.msg || '获取素材列表失败');
                }
            } catch (error) {
                console.error('获取素材列表失败:', error);
                this.$message.error('获取素材列表失败');
            } finally {
                this.materialLoading = false;
            }
        },

        resetMaterialQuery() {
            this.materialQuery = {
                version: '',
                visual_collection_id: '',
                page: 1,
                pageSize: 10
            };
            this.fetchMaterialList();
        },
        updateVisualCollectionName(id) {
            const found = this.enabledCollections.find(item => item.id === id);
            this.materialForm.visual_collection_name = found ? found.name : '';
            this.materialForm.visual_collection_id = id
            // enabledCollections 是你的列表

        },
        openMaterialDialog(row) {
            // 默认空表单项
            const defaultForm = {
                min_version: '',
                max_version: '',
                theme_tags: [],
                main_text_material: '',
                extra_text_materials: [],
                visual_collection_id: '',
                visual_collection_name: '',
                is_subscription_required: 0,
                thumbnail_url: '',
                original_image_url: '',
                video_url: '',
                sort_order: 0,
                upload_type: 1
            };

            if (row) {
                // 强制新建对象，防止响应式失效，先清空再赋值
                this.materialForm = {
                    ...defaultForm,
                    ...row,
                    // 保证 theme_tags/extra_text_materials 为数组
                    theme_tags: Array.isArray(row.theme_tags)
                        ? [...row.theme_tags]
                        : (typeof row.theme_tags === "string" && row.theme_tags
                            ? row.theme_tags.split(',').filter(Boolean)
                            : []),
                    extra_text_materials: Array.isArray(row.extra_text_materials)
                        ? [...row.extra_text_materials]
                        : (typeof row.extra_text_materials === "string" && row.extra_text_materials
                            ? row.extra_text_materials.split(',').filter(Boolean)
                            : []),
                    visual_collection_id: row.visual_collection_id !== undefined && row.visual_collection_id !== null
                        ? Number(row.visual_collection_id)
                        : '',
                };

                // 处理 upload_type 和互斥关系
                if (this.materialForm.original_image_url && !this.materialForm.video_url) {
                    this.materialForm.upload_type = 1;
                } else if (this.materialForm.video_url && !this.materialForm.original_image_url) {
                    this.materialForm.upload_type = 2;
                } else if (this.materialForm.original_image_url && this.materialForm.video_url) {
                    // 优先图片
                    this.materialForm.upload_type = 1;
                    this.materialForm.video_url = '';
                } else {
                    this.materialForm.upload_type = 1;
                }
            } else {
                // 新增：直接赋初始对象
                this.materialForm = { ...defaultForm };
            }

            this.materialDialogVisible = true;

            this.$nextTick(() => {
                if (this.$refs.materialForm) {
                    // 清除上次表单校验状态
                    this.$refs.materialForm.clearValidate();
                }
            });
        },


        // 保存素材（优化提交前的数据清理）
        async handleMaterialSave() {
            await this.$refs.materialForm.validate();
            this.materialSaveLoading = true;

            try {
                // 创建提交数据的副本，进行清理
                const submitData = { ...this.materialForm };

                // 根据upload_type清理不需要的字段
                if (submitData.upload_type === 1) {
                    // 选择图片时，清空视频字段
                    submitData.video_url = '';
                } else if (submitData.upload_type === 2) {
                    // 选择视频时，清空图片字段
                    submitData.original_image_url = '';
                }

                const { data } = await axios.post('https://xiaoshuchengzhang.com/node/Tarot/visualMaterial/save', submitData);

                if (data.code === 0) {
                    this.$message.success('保存成功');
                    this.materialDialogVisible = false;
                    this.fetchMaterialList();
                } else {
                    this.$message.error(data.msg || '保存失败');
                }
            } catch (error) {
                console.error('保存失败:', error);
                this.$message.error('保存失败');
            } finally {
                this.materialSaveLoading = false;
            }
        },

        deleteMaterial(row) {
            this.$confirm('确定要删除此素材吗？', '提示', { type: 'warning' }).then(async () => {
                try {
                    const { data } = await axios.post('https://xiaoshuchengzhang.com/node/Tarot/visualMaterial/delete', { id: row.id });

                    if (data.code === 0) {
                        this.$message.success('删除成功');
                        this.fetchMaterialList();
                    } else {
                        this.$message.error(data.msg || '删除失败');
                    }
                } catch (error) {
                    console.error('删除失败:', error);
                    this.$message.error('删除失败');
                }
            });
        },

        handleMaterialClose() {
            this.materialDialogVisible = false;
            this.$nextTick(() => {
                if (this.$refs.materialForm) {
                    this.$refs.materialForm.clearValidate();
                }
            });
        },

        parseCommaSeparated(str) {
            if (!str) return [];
            return str.split(',').map(item => item.trim()).filter(Boolean);
        }
    },
    mounted() {
        this.fetchCollectionList();
    }
}
</script>

<style scoped>
.clearfix:before,
.clearfix:after {
    display: table;
    content: "";
}

.clearfix:after {
    clear: both;
}

.el-card>>>.el-card__header {
    padding: 18px 20px;
    border-bottom: 1px solid #EBEEF5;
}

.el-table>>>th {
    background-color: #fafafa;
}

.dialog-footer {
    text-align: right;
}

.el-form-item {
    margin-bottom: 22px;
}

/* 表格行悬停效果 */
.el-table--enable-row-hover .el-table__body tr:hover>td {
    background-color: #f5f7fa;
}

/* 按钮组间距 */
.el-button+.el-button {
    margin-left: 10px;
}

/* 标签样式 */
.el-tag+.el-tag {
    margin-left: 4px;
}

.img-uploader {
    display: inline-block;
    width: 128px;
    height: 128px;
    border: 1.5px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    background: #fafbfc;
    text-align: center;
    vertical-align: middle;
}

.img-uploader-icon {
    font-size: 36px;
    color: #aaa;
    line-height: 128px;
    transition: color 0.2s;
}

.img-uploader:hover .img-uploader-icon {
    color: #409EFF;
}

.img-preview {
    width: 128px;
    height: 128px;
    object-fit: cover;
    border-radius: 6px;
    background: #fff;
}

.video-preview {
    width: 128px;
    height: 128px;
    object-fit: contain;
    border-radius: 6px;
    background: #222;
}

.img-delete {
    position: absolute;
    right: 5px;
    top: 5px;
    z-index: 9;
    padding: 0;
    border-radius: 50%;
}
</style>